<?php
/**
 * User: Tegic
 * Date: 2018/6/4
 * Time: 10:41
 */

namespace app\hander;

use Aliyun\Send as aliSend;

class SendMessageHelper
{
	
	
	private function __construct()
	{
		echo "";
	}
	
	/**
	 * 发送验证码
	 * @Function send
	 *
	 * @param $mobile 电话号码
	 * @param $type   类型  1注册 2登录
	 *
	 * @return mixed
	 * @Author   tegic
	 * @Time     2018/6/4 11:14
	 */
	static public function send($mobile, $type)
	{
		$code        = mt_rand(1000, 9999);
		$cachePrefix = 'mobileCode:'.$mobile .':'. $type;
		//检测是否已经发送过验证码
		/*if (cache($cachePrefix)) {
			return '验证码已发送';
		}*/
		//短信参数内容
		$data   = [
			'code' => $code,
		];
		$result = ( new aliSend(config('ali_config')) )->sendSms($mobile, $data);
		if ($result === true) {
			//将验证码存入缓存
			cache($cachePrefix, $code, config('app.message_overtime'));
			return $result;
		}
		return $result->Code;
	}
	
	/**
	 * 验证手机验证码是否正确
	 * @Function validateCode
	 *
	 * @param $mobile
	 * @param $type
	 * @param $code
	 *
	 * @return bool|string
	 * @Author   tegic
	 * @Time     2018/6/4 11:19
	 */
	static public function validateCode($mobile, $type, $code)
	{
		$cachePrefix = 'mobileCode:'.$mobile .':'. $type;;
		if (!cache($cachePrefix)) {
			return '验证码不存在或已过期';
		}
		if (cache($cachePrefix) !== $code) {
			return '验证码错误';
		}
		cache($cachePrefix, NULL);
		return true;
	}
}